<?php
/**
 * 用户地址管理
 * @version：1.0.0
 * Date: 2023/05/08 15:31
 */

namespace App\frontend\controllers\member;


use App\frontend\controllers\UserBaseController;
use App\frontend\models\AreaModel;
use App\frontend\models\MemberAddressModel;
use App\frontend\services\member\MemberAddressServices;
use Illuminate\Support\Facades\Validator;
use Psy\Util\Json;

class MemberAddressController extends UserBaseController
{

    private $thisClass = 'Member';

    private static $uid = 9;

    public function index()
    {
        //dd($list);
    }


    /**
     * 收货地址列表
     */
    public function getAddressList()
    {
       // $list = self::getData($this->thisClass, 'getAddressList',2);
        $memberId = self::$uid;
        $addressList = MemberAddressModel::getInstance()->getAddressList($memberId);
//        dd($addressList);
        return successJson('获取列表成功', $addressList);
    }

    /**
     * 修改收货地址
     */
    public function editAddress()
    {
        //$list = self::getData($this->thisClass, 'editAddress',2);

        $requestAddress = request()->all();
        $addressId = request()->input('address_id', 0);
        if ($requestAddress||$addressId) {
            $data = $requestAddress;
            //验证参数
            $res = MemberAddressServices::CheckAddressParam($data);
            if($res['status']!=0){
                return errorJson($res['msg']);
            }
            $addressModel = MemberAddressModel::getInstance()->getAddressAndUserById($addressId, self::$uid);
            if (!$addressModel) {
                return errorJson("未找到数据或已删除");
            }
            //默认地址处理
            $isDefault = $data['isdefault'];
            if (empty($addressModel->isdefault) && $isDefault) {
                $addressModel->isdefault = 1;
                //未附值
                MemberAddressModel::getInstance()->cancelDefaultAddress(self::$uid);
            }

            //更新
            $data['uid'] = self::$uid;
            unset($data['address_id']);
            $res = MemberAddressModel::getInstance()->updateSave(['id'=>$addressId],$data);
            if ($res) {
                return successJson('修改收货地址成功');
            } else {
                return errorJson("写入数据出错，请重试！");
            }
        }
        return errorJson("未获取到数据，请重试！");
    }

    /**
     * 增加收货地址
     */
    public function addAddress()
    {
        //$list = self::getData($this->thisClass, 'addAddress',2);

        $requestAddress = request()->all();
        if ($requestAddress) {
            $data = $requestAddress;
            //验证参数
            $res = MemberAddressServices::CheckAddressParam($data);
            if($res['status']!=0){
                return errorJson($res['msg']);
            }
            //添加
            $data['uid'] = self::$uid;
            $res = MemberAddressModel::getInstance()->addSave($data);
            if ($res) {
                return successJson('新增地址成功');
            } else {
                return errorJson("数据写入出错，请重试！");
            }
        }
        return errorJson("未获取到数据，请重试！");
    }




    /**
     * 获取下单页要编辑的地址信息
     * @return JsonResponse
     */
    public function getOneAddress()
    {
        $id = request()->input('address_id', 0);

        if (empty($id)) {
            return errorJson('参数为空');
        }
        $address = MemberAddressModel::getInstance()->getAddressById($id);
        if (empty($address)) {
            return errorJson('地址不存在');
        }
        return successJson('信息', $address);
    }

    /**
     * 地址JSON数据接口
     * @return Json
     */
    public function areaAll()
    {
        $address_list = AreaModel::getAreaDatas();
        if (!$address_list) {
            return errorJson('数据获取失败，请联系管理员！');
        }
        $msg = '数据获取成功';
        return successJson($msg,$address_list);
    }



    /**
     * 修改默认收货地址
     * @return Json
     */
    public function setDefault()
    {
        $memberId = self::$uid;
        $addressId = request()->input('address_id', 0);
        $addressModel = MemberAddressModel::getInstance()->getAddressById($addressId);
        if (empty($addressModel)) {
            return errorJson('未找到数据或已删除，请重试！');
        }
        if ($addressModel->isdefault) {
            return errorJson('默认地址不支持取消，请编辑或修改其他默认地址');
        }

        $addressModel->isdefault = 1;
        MemberAddressModel::getInstance()->cancelDefaultAddress($memberId);

        if ($addressModel->save()) {
            return successJson('修改默认地址成功');
        } else {
            return errorJson('修改失败，请刷新重试！');
        }
    }


    /**
     * 移除会员收货地址
     * @return Json
     */
    public function deleteAddress()
    {
        $addressId = request()->input('address_id', 0);
        $addressModel = MemberAddressModel::getInstance()->getAddressById($addressId);
        if (!$addressModel || $addressModel->uid != self::$uid) {
            return errorJson("未找到数据或已删除");
        }
        //需要考虑删除默认地址选择其他地址改为默认
        $result = MemberAddressModel::getInstance()->destroyAddress($addressId);
        if ($result) {
            return successJson();
        } else {
            return errorJson("数据写入出错，删除失败！");
        }
    }


    /**
     * 服务地址接口数据重构
     * @param $address
     * @return array[]
     */
    private function addressService($address)
    {
        $province = [];
        $city = [];
        $district = [];
        foreach ($address as $key) {
            if ($key['parentid'] == 0 && $key['level'] == 1) {
                $province[] = $key;
            } elseif ($key['parentid'] != 0 && $key['level'] == 2) {
                $city[] = $key;
            } else {
                $district[] = $key;
            }
        }
        return array(
            'province' => $province,
            'city'     => $city,
            'district' => $district,
        );
    }


    /**
     * 修改地理位置（经纬度）接口  ps同城配送使用
     * request address_id 地址ID
     * request latitude 纬度
     * request longitude 经度
     * @return \Illuminate\Http\JsonResponse
     */
    public function updateLocation()
    {
        $addressId = request()->input('address_id', 0);
        $addressModel = MemberAddressModel::instance()->getAddressAndUserById($addressId, self::$uid);
        $addressModel->latitude = request()->input('latitude') ?: '';
        $addressModel->longitude = request()->input('longitude') ?: '';
        if ($addressModel->save()) {
            return successJson('修改地理位置成功', $addressModel->toArray());
        } else {
            return errorJson("写入数据出错，请重试！");
        }
    }

}
